/**
 * Created by 丸子 on 2018/7/19 0019.
 */
import axios from 'axios'
import Vue from 'vue'
import {GETTERS, ACTIONS, MUTATIONS} from './types'
import {getSessionStorageItem, setSessionStorageItem} from '../../util'
import {SESSION_STORAGE__TOKEN, SESSION_STORAGE__USER_INFO} from '../../util/constant'

function setAxiosToken(token){
  console.log('setAxiosToken', token)
  if (token) {
    axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
  } else {
    axios.defaults.headers.common['Authorization'] = ''
  }
}

let actions = {
  [ACTIONS.fetchUserInfo] ({commit}) {
    return axios.get('/front/get/SysUser/info')
      .then((response) => {
        const {code, data: userInfo, message} = response.data
        if (code === '200') {
          commit(MUTATIONS.setUserInfo, userInfo)
        } else if (code === '400') { // 未登录
          commit(MUTATIONS.setUserInfo, null)
        } else {
          commit(MUTATIONS.setUserInfo, null)
          Vue.prototype.$message.error(message || '获取登录状态失败')
        }
        return response.data
      })
  },
  [ACTIONS.logout] ({commit}) {
    commit(MUTATIONS.setToken, {})
    commit(MUTATIONS.setUserInfo, {})
  },

  [ACTIONS.login] ({commit}, userInfo) {
    commit(MUTATIONS.setUserInfo, userInfo)
  },
  [ACTIONS.getTree] ({commit}) {
    // 导航树
    return axios.get('/adminapi/rule/ruleTree')
      .then(response => {
        const {status, msg,data} = response.data
        if (status !== 1) {
          Vue.prototype.$message.error(msg || '请求数据失败')
        } else {
          commit(MUTATIONS.setMenus, data)
        }
      }).catch(Vue.prototype.$alertAxiosError)
  },
  async [ACTIONS.checkToken] ({commit, state}) {
    if (state.token) {
      return axios.get('/token-manager/unchk/auth/checktoken')
        .then((response) => {
          const {code, data: isTokenValid, msg} = response.data
          if (code === '200') {
            if (!isTokenValid) {
              commit(MUTATIONS.setToken, {token: ''})
            }
          } else {
            Vue.prototype.$message.error(msg || '获取登录状态失败')
          }
        })
    }
  }
}

let getters = {
  [GETTERS.userInfo]: state => state.userInfo,
  [GETTERS.token]:state=>state.token,
  [GETTERS.isLogged]: state => !!state.userInfo,
  [GETTERS.menus]: state => state.menus
}

let mutations = {
  [MUTATIONS.setUserInfo]: (state, userInfo) => {
    state.userInfo = userInfo
    setSessionStorageItem(SESSION_STORAGE__USER_INFO, userInfo)
  },
  [MUTATIONS.setMenus]: (state, menus) => {
    state.menus = menus
  },
  [MUTATIONS.setToken]: (state, {token}) => {
    setSessionStorageItem(SESSION_STORAGE__TOKEN, token)

    setAxiosToken(token)
    state.token = token
  }
}
// setSessionStorageItem(SESSION_STORAGE__TOKEN, '11111')
export default function () {
  const state = {
    userInfo: getSessionStorageItem(SESSION_STORAGE__USER_INFO, {}),
    token: getSessionStorageItem(SESSION_STORAGE__TOKEN, ''),
    menus: []
  }

  setAxiosToken(state.token)
  return {
    state,
    actions,
    getters,
    mutations
  }
}
